﻿-- =========================================================================================================
-- Author:		MICHAEL RITACCO
-- Copyright:	2010 MEKHANO GROUP LLC
-- Version:		08/21/2010 1.0
-- =========================================================================================================
CREATE PROCEDURE [flcrTM].[api_tm_device_dml_mrg]
	(@TVP flcr.DEVICE_UDT READONLY)

AS
BEGIN TRY

	MERGE	[flcrTm].[DEVICE] A
	USING	[flcr].[DEVICE] B
	   ON	A.[DEVICE_ID] = B.[DEVICE_ID]
	  AND	[flcrTm].GetTMPeriodKey(B.[AUDIT_MOD_DTTM]) = A.[TIME_KEY]
	 WHEN NOT MATCHED BY TARGET THEN
			INSERT VALUES
			([flcrTm].GetTMPeriodKey(B.[AUDIT_MOD_DTTM])
			,B.[DEVICE_ID]
			,B.[AUDIT_USER]
			,B.[AUDIT_DTTM]
			,b.[AUDIT_DTTM_TZ]
			,B.[AUDIT_MOD_USER]
			,B.[AUDIT_MOD_DTTM]
			,B.[AUDIT_MOD_DTTM_TZ]
			,B.[RLS_MASK]
			,B.[RLS_OWNER]
			,B.[WRKFL_ITEM_ID]
			,B.[WRKFL_STATUS_ID]
			,B.[ACTIVE_FLG]
			,B.[DEVICE_ASSET_NAME]
			,B.[DEVICE_SERIAL_NUM]
			,B.[DEVICE_ASSET_TAG]
			,B.[PARENT_ID]
			,B.[DEVICE_TYPE]
			,B.[DEVICE_PLATFORM_ID]
			,B.[DOMAIN_ID]
			,B.[ORG_ID]
			,B.[RESOURCE_ID]
			,B.[SLA_ID]
			,B.[FACILITY_ID]
			,B.[ENV_ID])
	 WHEN MATCHED AND (b.DEVICE_ID IN (SELECT [DEVICE_ID] FROM @TVP)) THEN
			UPDATE SET
			A.[AUDIT_MOD_USER] = B.[AUDIT_MOD_USER]
			,A.[AUDIT_MOD_DTTM] = B.[AUDIT_MOD_DTTM]
			,A.[AUDIT_MOD_DTTM_TZ] = B.[AUDIT_MOD_DTTM_TZ]
			,A.[RLS_MASK] = B.[RLS_MASK]
			,A.[RLS_OWNER] = B.[RLS_OWNER]
			,A.[WRKFL_ITEM_ID] =B.[WRKFL_ITEM_ID]
			,A.[WRKFL_STATUS_ID] = B.[WRKFL_STATUS_ID]
			,A.[ACTIVE_FLG] = B.[ACTIVE_FLG]
			,A.[DEVICE_ASSET_NAME] = B.[DEVICE_ASSET_NAME]
			,A.[DEVICE_SERIAL_NUM] = B.[DEVICE_SERIAL_NUM]
			,A.[DEVICE_ASSET_TAG] = B.[DEVICE_ASSET_TAG]
			,A.[PARENT_ID] = B.[PARENT_ID]
			,A.[DEVICE_TYPE] = B.[DEVICE_TYPE]
			,A.[DEVICE_PLATFORM_ID] = B.[DEVICE_PLATFORM_ID]
			,A.[DOMAIN_ID] = B.[DOMAIN_ID]
			,A.[SLA_ID] = B.[SLA_ID]
			,A.[FACILITY_ID] = B.[FACILITY_ID]
			,A.[ENV_ID] = B.[ENV_ID];		
			
END TRY
BEGIN CATCH
	EXEC [flcr].[utl_GetDBError];
END CATCH